# -*- coding:utf-8 -*-
from Tkinter import *
from ttk import *

from devices_frame import DeviceControl
from filter_frame import LogFilter
from utils.adb_logcat import AdbLogcat
from utils.adb_utils import AdbUtils
from utils.format_util import FormatUtil
from utils.ui_utils import EasyText, UICheckbutton


class LogcatMain:
    def __init__(self, master):
        self.adb = AdbUtils()
        self.logcat = AdbLogcat()
        self.formatter = FormatUtil()

        self.master = Frame(master)
        self.master.pack(side=TOP, anchor=W, expand=True, fill=BOTH, padx=4, pady=4)

        self.init_devices_selector()
        self.log_filter = self.init_log_filter()

        self.frm_ctrl = Frame(self.master)
        self.frm_ctrl.pack(side=TOP, anchor=W, fill=X)
        Button(self.frm_ctrl, text="Start", command=self.start_logcat).pack(side=LEFT, anchor=W, padx=4, pady=4)
        Button(self.frm_ctrl, text="Stop", command=self.stop_logcat).pack(side=LEFT, anchor=W, padx=4, pady=4)
        Button(self.frm_ctrl, text="Clear", command=self.clear_log).pack(side=LEFT, anchor=W, padx=4, pady=4)

        self.wrap_logcat_check = UICheckbutton(self.frm_ctrl, text="换行", checked=False, command=self.warp_logcat)

        self.log_memo = self.init_log_memo()

    def init_devices_selector(self):
        DeviceControl(self.master, self.adb.adb_devices)

    def init_log_filter(self):
        return LogFilter(self.master)

    def init_log_memo(self):
        return EasyText(self.master)

    def start_logcat(self):
        self.clear_log()
        filter_str = self.log_filter.get_filter()
        print filter_str
        # self.adb.start_logcat(filter_str, self.log_print)
        self.logcat.set_filter(filter_str)
        self.logcat.start(self.callback_print)

    def stop_logcat(self):
        self.logcat.stop()

    def clear_log(self):
        self.log_memo.clear_text()

    def warp_logcat(self):
        self.log_memo.set_warp(self.wrap_logcat_check.get_checked())

    def callback_print(self, log_line):
        if self.log_filter.filter_mode == "PPKV":
            log_line = self.formatter.logcat_format(log_line)
        self.log_memo.append_text(log_line+"\n")

if __name__ == "__main__":
    root = Tk()
    root.geometry('600x480+200+200')  # 是x 不是*
    "设置窗口是否可调整宽度和高度"
    # root.resizable(width=True, height=True)  # 宽不可变, 高可变,默认为True
    "设置窗口标题"
    root.title("Logcat Tool")

    frame_root = Frame(root)
    frame_root.pack(side=TOP, fill=BOTH, expand=True)

    adb = LogcatMain(frame_root)

    root.mainloop()
